﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using HealthExaminationSys.Common;
using System.Windows.Forms;
using Microsoft.Data.ConnectionUI;

namespace HealthExaminationSys.DBUtility
{
    /// <summary>
    /// 数据库连接设置相关类
    /// </summary>
    public class DbConfig
    {
        /// <summary>
        /// ConnStr名称（设置中ConnStr的名称）
        /// </summary>
        protected virtual string ConnStr_Name { get { return "ConnStr"; } }
        /// <summary>
        /// DataSourceName名称（设置中DataSourceName的名称）
        /// </summary>
        protected virtual string DataSourceName_Name { get { return "DataSourceName"; } }
        /// <summary>
        /// 显示数据库连接设置的模式对话框。
        /// </summary>
        /// <returns>System.Windows.Forms.DialogResult 值之一。</returns>
        public DialogResult ShowDialog()
        {
            DataConnectionDialog dlg = new DataConnectionDialog();
            DataSource.AddStandardDataSources(dlg);
            try
            {
                var dss = dlg.DataSources.FirstOrDefault(ds => ds.Name == AppConfig.GetValue(DataSourceName_Name));
                dlg.SelectedDataSource = dss;
                dlg.SelectedDataProvider = dss.Providers.FirstOrDefault(dp => dp.Name == AppConfig.GetConnStrSetting(ConnStr_Name).ProviderName);
                dlg.ConnectionString = AppConfig.GetConnStrSetting(ConnStr_Name).ConnectionString;
            }
            catch { }
            var val = DataConnectionDialog.Show(dlg);
            if (val == System.Windows.Forms.DialogResult.OK)
            {
                AppConfig.SetConnStrSetting(ConnStr_Name, dlg.ConnectionString, dlg.SelectedDataProvider.Name);
                AppConfig.SetValue(DataSourceName_Name, dlg.SelectedDataSource.Name);
            }
            return val;
        }
        /// <summary>
        /// 表示连接字符串配置文件节中的单个命名连接字符串。
        /// </summary>
        ConnectionStringSettings ConnStrSetting { get { return AppConfig.GetConnStrSetting(ConnStr_Name); } }
        /// <summary>
        /// 获取连接字符串。
        /// </summary>
        internal string ConnString { get { return ConnStrSetting.ConnectionString; } }
        /// <summary>
        /// 获取提供程序名称属性。
        /// </summary>
        internal string ProviderName { get { return ConnStrSetting.ProviderName; } }
    }
    
}
